#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define MAX 1024;

main(int argc, char *argv[]){
	int i;
	int check[3];
		
	for(i=0; i<argv[i]; i++){
		if(!strcmp(argv[i], "<"))
			check[0]=1;
		else if(!strcmp(argv[i], ">"))
			check[1]=1;
		else if(!strcmp(argv[i], ">>"))
			check[2]=1;
	}
	if((check[1]==1 || check[2]==1)){
		redirect_out(argv, check[1]);
	}
	if(check[0]==1){
		redirect_in(argv);
	}
}
void redirect_in(char *argv[]){

	int i, fd;

	for(i=0; i<argv[i]; i++) {   // redirection check	
		if(!strcmp(argv[i], "<"))
			break;
	}
	if(argv[i]){
		if((fd=open(argv[i+1], O_RDONLY))==-1){ //file open
			perror("open failed");
			return;
		}
		dup2(fd, 0);
		argv[i] = NULL;
		argv[i+1] = NULL;
		close(fd);
	}
}

void redirect_out(char *argv[], int check){

	int i, fd;

	for(i=0; i<argv[i]; i++){
		if(!strcmp(argv[i], ">")){
			break;
		}
		else if(!strcmp(argv[i], ">>")){
			break;	
		}
	}
	if(check==1){
		if((fd=open(argv[i+1], O_WRONLY | O_CREAT | O_TRUNC, 0644))==-1){
			perror("open failed");
			return;
		}
		dup2(fd, 1);
		argv[i] = NULL;
		argv[i+1] = NULL;
		close(fd);
	}
	else{
		if((fd=open(argv[i+1], O_WRONLY | O_APPEND, 0644))==-1){
			perror("open failed");
			return;
		}
		dup2(fd, 1);
		argv[i] = NULL;
		argv[i+1] = NULL;
		close(fd);
	}
}


















